Trò chơi giống như Rogue 2D sử dụng Unity
- Player.cs
- Scripts /
- _Complete-Game /
- Assets /
- project /
2 using System.Collections;
3 using UnityEngine.UI; //Allows us to use UI.
4 using UnityEngine.SceneManagement;
5
6 namespace Completed
7 {
8 //Player inherits from MovingObject, our base class for objects that can move, Enemy also inherits from this.
9 public class Player : MovingObject
10 {
11 public float restartLevelDelay = 1f; //Delay time in seconds to restart level.
12 public int pointsPerFood = 10; //Number of points to add to player food points when picking up a food object.
13 public int pointsPerSoda = 20; //Number of points to add to player food points when picking up a soda object.
14 public int wallDamage = 1; //How much damage a player does to a wall when chopping it.
15 public Text foodText; //UI Text to display current player food total.
16 public AudioClip moveSound1; //1 of 2 Audio clips to play when player moves.
17 public AudioClip moveSound2; //2 of 2 Audio clips to play when player moves.
18 public AudioClip eatSound1; //1 of 2 Audio clips to play when player collects a food object.
19 public AudioClip eatSound2; //2 of 2 Audio clips to play when player collects a food object.
20 public AudioClip drinkSound1; //1 of 2 Audio clips to play when player collects a soda object.
21 public AudioClip drinkSound2; //2 of 2 Audio clips to play when player collects a soda object.
22 public AudioClip gameOverSound; //Audio clip to play when player dies.
23
24 private Animator animator; //Used to store a reference to the Player's animator component.
25 private int food; //Used to store player food points total during level.
26 #if UNITY_IOS || UNITY_ANDROID || UNITY_WP8 || UNITY_IPHONE
27 private Vector2 touchOrigin = -Vector2.one; //Used to store location of screen touch origin for mobile controls.
28 #endif
29
30
31 //Start overrides the Start function of MovingObject
32 protected override void Start ()
33 {
34 //Get a component reference to the Player's animator component
35 animator = GetComponent<Animator>();
36
37 //Get the current food point total stored in GameManager.instance between levels.
38 food = GameManager.instance.playerFoodPoints;
39
40 //Set the foodText to reflect the current player food total.
41 foodText.text = "Food: " + food;
42
43 //Call the Start function of the MovingObject base class.
44 base.Start ();
45 }
46
47
48 //This function is called when the behaviour becomes disabled or inactive.
49 private void OnDisable ()
50 {
51 //When Player object is disabled, store the current local food total in the GameManager so it can be re-loaded in next level.
52 GameManager.instance.playerFoodPoints = food;
53 }
54
55
56 private void Update ()
57 {
58 //If it's not the player's turn, exit the function.
59 if(!GameManager.instance.playersTurn) return;
60
61 int horizontal = 0; //Used to store the horizontal move direction.
62 int vertical = 0; //Used to store the vertical move direction.
63
64 //Check if we are running either in the Unity editor or in a standalone build.
65 #if UNITY_STANDALONE || UNITY_WEBPLAYER
66
67 //Get input from the input manager, round it to an integer and store in horizontal to set x axis move direction
68 horizontal = (int) (Input.GetAxisRaw ("Horizontal"));
69
70 //Get input from the input manager, round it to an integer and store in vertical to set y axis move direction
71 vertical = (int) (Input.GetAxisRaw ("Vertical"));
72
73 //Check if moving horizontally, if so set vertical to zero.
74 if(horizontal != 0)
75 {
76 vertical = 0;
77 }
78 //Check if we are running on iOS, Android, Windows Phone 8 or Unity iPhone
79 #elif UNITY_IOS || UNITY_ANDROID || UNITY_WP8 || UNITY_IPHONE
80
81 //Check if Input has registered more than zero touches
82 if (Input.touchCount > 0)
83 {
84 //Store the first touch detected.
85 Touch myTouch = Input.touches[0];
86
87 //Check if the phase of that touch equals Began
88 if (myTouch.phase == TouchPhase.Began)
89 {
90 //If so, set touchOrigin to the position of that touch
91 touchOrigin = myTouch.position;
92 }
93
94 //If the touch phase is not Began, and instead is equal to Ended and the x of touchOrigin is greater or equal to zero:
95 else if (myTouch.phase == TouchPhase.Ended && touchOrigin.x >= 0)
96 {
97 //Set touchEnd to equal the position of this touch
98 Vector2 touchEnd = myTouch.position;
99
100 //Calculate the difference between the beginning and end of the touch on the x axis.
101 float x = touchEnd.x - touchOrigin.x;
102
103 //Calculate the difference between the beginning and end of the touch on the y axis.
104 float y = touchEnd.y - touchOrigin.y;
105
106 //Set touchOrigin.x to -1 so that our else if statement will evaluate false and not repeat immediately.
107 touchOrigin.x = -1;
108
109 //Check if the difference along the x axis is greater than the difference along the y axis.
110 if (Mathf.Abs(x) > Mathf.Abs(y))
111 //If x is greater than zero, set horizontal to 1, otherwise set it to -1
112 horizontal = x > 0 ? 1 : -1;
113 else
114 //If y is greater than zero, set horizontal to 1, otherwise set it to -1
115 vertical = y > 0 ? 1 : -1;
116 }
117 }
118
119 #endif //End of mobile platform dependendent compilation section started above with #elif
120 //Check if we have a non-zero value for horizontal or vertical
121 if(horizontal != 0 || vertical != 0)
122 {
123 //Call AttemptMove passing in the generic parameter Wall, since that is what Player may interact with if they encounter one (by attacking it)
124 //Pass in horizontal and vertical as parameters to specify the direction to move Player in.
125 AttemptMove<Wall> (horizontal, vertical);
126 }
127 }
128
129 //AttemptMove overrides the AttemptMove function in the base class MovingObject
130 //AttemptMove takes a generic parameter T which for Player will be of the type Wall, it also takes integers for x and y direction to move in.
131 protected override void AttemptMove <T> (int xDir, int yDir)
132 {
133 //Every time player moves, subtract from food points total.
134 food--;
135
136 //Update food text display to reflect current score.
137 foodText.text = "Food: " + food;
138
139 //Call the AttemptMove method of the base class, passing in the component T (in this case Wall) and x and y direction to move.
140 base.AttemptMove <T> (xDir, yDir);
141
142 //Hit allows us to reference the result of the Linecast done in Move.
143 RaycastHit2D hit;
144
145 //If Move returns true, meaning Player was able to move into an empty space.
146 if (Move (xDir, yDir, out hit))
147 {
148 //Call RandomizeSfx of SoundManager to play the move sound, passing in two audio clips to choose from.
149 SoundManager.instance.RandomizeSfx (moveSound1, moveSound2);
150 }
151
152 //Since the player has moved and lost food points, check if the game has ended.
153 CheckIfGameOver ();
154
155 //Set the playersTurn boolean of GameManager to false now that players turn is over.
156 GameManager.instance.playersTurn = false;
157 }
158
159
160 //OnCantMove overrides the abstract function OnCantMove in MovingObject.
161 //It takes a generic parameter T which in the case of Player is a Wall which the player can attack and destroy.
162 protected override void OnCantMove <T> (T component)
163 {
164 //Set hitWall to equal the component passed in as a parameter.
165 Wall hitWall = component as Wall;
166
167 //Call the DamageWall function of the Wall we are hitting.
168 hitWall.DamageWall (wallDamage);
169
170 //Set the attack trigger of the player's animation controller in order to play the player's attack animation.
171 animator.SetTrigger ("playerChop");
172 }
173
174
175 //OnTriggerEnter2D is sent when another object enters a trigger collider attached to this object (2D physics only).
176 private void OnTriggerEnter2D (Collider2D other)
177 {
178 //Check if the tag of the trigger collided with is Exit.
179 if(other.tag == "Exit")
180 {
181 //Invoke the Restart function to start the next level with a delay of restartLevelDelay (default 1 second).
182 Invoke ("Restart", restartLevelDelay);
183
184 //Disable the player object since level is over.
185 enabled = false;
186 }
187
188 //Check if the tag of the trigger collided with is Food.
189 else if(other.tag == "Food")
190 {
191 //Add pointsPerFood to the players current food total.
192 food += pointsPerFood;
193
194 //Update foodText to represent current total and notify player that they gained points
195 foodText.text = "+" + pointsPerFood + " Food: " + food;
196
197 //Call the RandomizeSfx function of SoundManager and pass in two eating sounds to choose between to play the eating sound effect.
198 SoundManager.instance.RandomizeSfx (eatSound1, eatSound2);
199
200 //Disable the food object the player collided with.
201 other.gameObject.SetActive (false);
202 }
203
204 //Check if the tag of the trigger collided with is Soda.
205 else if(other.tag == "Soda")
206 {
207 //Add pointsPerSoda to players food points total
208 food += pointsPerSoda;
209
210 //Update foodText to represent current total and notify player that they gained points
211 foodText.text = "+" + pointsPerSoda + " Food: " + food;
212
213 //Call the RandomizeSfx function of SoundManager and pass in two drinking sounds to choose between to play the drinking sound effect.
214 SoundManager.instance.RandomizeSfx (drinkSound1, drinkSound2);
215
216 //Disable the soda object the player collided with.
217 other.gameObject.SetActive (false);
218 }
219 }
220
221
222 //Restart reloads the scene when called.
223 private void Restart ()
224 {
225 //Load the last scene loaded, in this case Main, the only scene in the game. And we load it in "Single" mode so it replace the existing one
226 //and not load all the scene object in the current scene.
227 SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex, LoadSceneMode.Single);
228 }
229
230
231 //LoseFood is called when an enemy attacks the player.
232 //It takes a parameter loss which specifies how many points to lose.
233 public void LoseFood (int loss)
234 {
235 //Set the trigger for the player animator to transition to the playerHit animation.
236 animator.SetTrigger ("playerHit");
237
238 //Subtract lost food points from the players total.
239 food -= loss;
240
241 //Update the food display with the new total.
242 foodText.text = "-"+ loss + " Food: " + food;
243
244 //Check to see if game has ended.
245 CheckIfGameOver ();
246 }
247
248
249 //CheckIfGameOver checks if the player is out of food points and if so, ends the game.
250 private void CheckIfGameOver ()
251 {
252 //Check if food point total is less than or equal to zero.
253 if (food <= 0)
254 {
255 //Call the PlaySingle function of SoundManager and pass it the gameOverSound as the audio clip to play.
256 SoundManager.instance.PlaySingle (gameOverSound);
257
258 //Stop the background music.
259 SoundManager.instance.musicSource.Stop();
260
261 //Call the GameOver function of GameManager.
262 GameManager.instance.GameOver ();
263 }
264 }
265 }
266 }
using UnityEngine.UI; Allows us to use UI.
Player inherits from MovingObject, our base class for objects that can move, Enemy also inherits from this.
public float restartLevelDelay = 1f; Delay time in seconds to restart level.
public int pointsPerFood = 10; Number of points to add to player food points when picking up a food object.
public int pointsPerSoda = 20; Number of points to add to player food points when picking up a soda object.
public int wallDamage = 1; How much damage a player does to a wall when chopping it.
public Text foodText; UI Text to display current player food total.
public AudioClip moveSound1; 1 of 2 Audio clips to play when player moves.
public AudioClip moveSound2; 2 of 2 Audio clips to play when player moves.
public AudioClip eatSound1; 1 of 2 Audio clips to play when player collects a food object.
public AudioClip eatSound2; 2 of 2 Audio clips to play when player collects a food object.
public AudioClip drinkSound1; 1 of 2 Audio clips to play when player collects a soda object.
public AudioClip drinkSound2; 2 of 2 Audio clips to play when player collects a soda object.
public AudioClip gameOverSound; Audio clip to play when player dies.
private Animator animator; Used to store a reference to the Player's animator component.
private int food; Used to store player food points total during level.
private Vector2 touchOrigin = -Vector2.one; Used to store location of screen touch origin for mobile controls.
Start overrides the Start function of MovingObject
Get a component reference to the Player's animator component
Get the current food point total stored in GameManager.instance between levels.
Set the foodText to reflect the current player food total.
Call the Start function of the MovingObject base class.
This function is called when the behaviour becomes disabled or inactive.
When Player object is disabled, store the current local food total in the GameManager so it can be re-loaded in next level.
If it's not the player's turn, exit the function.
int horizontal = 0; Used to store the horizontal move direction.
int vertical = 0; Used to store the vertical move direction.
Check if we are running either in the Unity editor or in a standalone build.
Get input from the input manager, round it to an integer and store in horizontal to set x axis move direction
Get input from the input manager, round it to an integer and store in vertical to set y axis move direction
Check if moving horizontally, if so set vertical to zero.
Check if we are running on iOS, Android, Windows Phone 8 or Unity iPhone
Check if Input has registered more than zero touches
Store the first touch detected.
Check if the phase of that touch equals Began
If so, set touchOrigin to the position of that touch
If the touch phase is not Began, and instead is equal to Ended and the x of touchOrigin is greater or equal to zero:
Set touchEnd to equal the position of this touch
Calculate the difference between the beginning and end of the touch on the x axis.
Calculate the difference between the beginning and end of the touch on the y axis.
Set touchOrigin.x to -1 so that our else if statement will evaluate false and not repeat immediately.
Check if the difference along the x axis is greater than the difference along the y axis.
If x is greater than zero, set horizontal to 1, otherwise set it to -1
If y is greater than zero, set horizontal to 1, otherwise set it to -1
#endif End of mobile platform dependendent compilation section started above with #elif
Check if we have a non-zero value for horizontal or vertical
Call AttemptMove passing in the generic parameter Wall, since that is what Player may interact with if they encounter one (by attacking it)
Pass in horizontal and vertical as parameters to specify the direction to move Player in.
AttemptMove overrides the AttemptMove function in the base class MovingObject
AttemptMove takes a generic parameter T which for Player will be of the type Wall, it also takes integers for x and y direction to move in.
Every time player moves, subtract from food points total.
Update food text display to reflect current score.
Call the AttemptMove method of the base class, passing in the component T (in this case Wall) and x and y direction to move.
Hit allows us to reference the result of the Linecast done in Move.
If Move returns true, meaning Player was able to move into an empty space.
Call RandomizeSfx of SoundManager to play the move sound, passing in two audio clips to choose from.
Since the player has moved and lost food points, check if the game has ended.
Set the playersTurn boolean of GameManager to false now that players turn is over.
OnCantMove overrides the abstract function OnCantMove in MovingObject.
It takes a generic parameter T which in the case of Player is a Wall which the player can attack and destroy.
Set hitWall to equal the component passed in as a parameter.
Call the DamageWall function of the Wall we are hitting.
Set the attack trigger of the player's animation controller in order to play the player's attack animation.
OnTriggerEnter2D is sent when another object enters a trigger collider attached to this object (2D physics only).
Check if the tag of the trigger collided with is Exit.
Invoke the Restart function to start the next level with a delay of restartLevelDelay (default 1 second).
Disable the player object since level is over.
Check if the tag of the trigger collided with is Food.
Add pointsPerFood to the players current food total.
Update foodText to represent current total and notify player that they gained points
Call the RandomizeSfx function of SoundManager and pass in two eating sounds to choose between to play the eating sound effect.
Disable the food object the player collided with.
Check if the tag of the trigger collided with is Soda.
Add pointsPerSoda to players food points total
Update foodText to represent current total and notify player that they gained points
Call the RandomizeSfx function of SoundManager and pass in two drinking sounds to choose between to play the drinking sound effect.
Disable the soda object the player collided with.
Restart reloads the scene when called.
Load the last scene loaded, in this case Main, the only scene in the game. And we load it in "Single" mode so it replace the existing one
and not load all the scene object in the current scene.
LoseFood is called when an enemy attacks the player.
It takes a parameter loss which specifies how many points to lose.
Set the trigger for the player animator to transition to the playerHit animation.
Subtract lost food points from the players total.
Update the food display with the new total.
Check to see if game has ended.
CheckIfGameOver checks if the player is out of food points and if so, ends the game.
Check if food point total is less than or equal to zero.
Call the PlaySingle function of SoundManager and pass it the gameOverSound as the audio clip to play.
Stop the background music.
Call the GameOver function of GameManager.